package nccloud.fct.ap.servlet;

import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.bs.wsdl.pub.DataInfoHelper;
import nc.itf.wsdl.pub.IWSDLLogger;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 付款合同查询接口接口
 *
 * @Author ouyanggx
 * @Date 2025/8/7
 * */
public class FctApQuery extends HttpServlet implements IHttpServletAdaptor {

    private BaseDAO baseDAO = null;

    private BaseDAO getBaseDAO() throws Exception
    {
        if (baseDAO == null)
        {
            baseDAO = new BaseDAO();
        }
        return baseDAO;
    }

    @Override
    public void doAction(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        request.setCharacterEncoding("UTF-8");/** 设置请求编码 */
        response.setContentType("text/html");/** 设置响应类型 */
        response.setCharacterEncoding("UTF-8");/** 设置响应编码 */

        UFDateTime serverTime = DataInfoHelper.getServerTime();// 服务器时间
        IWSDLLogger iLogger = NCLocator.getInstance().lookup(IWSDLLogger.class);// 日志接口
        JSONObject req = new JSONObject();
        JSONObject resp = new JSONObject();

        try {
            loginNcSystem();// 模拟登录
            String dataSource = request.getParameter("datasource");// 指定数据源
            if (StringUtils.isBlank(dataSource)) {
                throw new ServletException("datasource参数不能为空");
            }
            InvocationInfoProxy.getInstance().setUserDataSource(dataSource);
            InvocationInfoProxy.getInstance().setGroupId("0001A210000000000JB9");

            // 接口数据
            String requestStr = readRequest(request);
            req =  JSONObject.parseObject(requestStr);

            /**
             * 合同处理
             */
            String action = req.getString("action");
            if("QUERY".equals(action)){
                doQuery(req, resp);
            }else{
                resp.put("issuccess", "N");
                resp.put("msg", "无法识别传输的接口动作");
            }
        } catch (Exception e) {
            resp.put("issuccess", "N");
            resp.put("msg", e.getMessage());
        }finally {

            // 记录日志
            try {
                iLogger.saveLogger_RequiresNew(serverTime, req, resp);
            } catch (BusinessException e) {
                throw new RuntimeException(e);
            }
        }

        response.getWriter().print(resp);
    }

    /**
     * 保存合同
     * @return
     * @throws BusinessException
     */
    public void doQuery(JSONObject req, JSONObject resp) throws Exception
    {
        JSONObject apVO = req.getJSONObject("apVO");
        String vbillcode = apVO.getString("vbillcode");
        String sql = "SELECT pk_fct_ap FROM fct_ap WHERE vbillcode ='" + vbillcode + "' and NVL(dr,0) = 0 ";
        String pk_fct_ap = (String) this.getBaseDAO().executeQuery(sql, new ColumnProcessor());
        if (StringUtils.isBlank(pk_fct_ap)){
            resp.put("issuccess", "N");
            resp.put("msg", "未查询到["+vbillcode+"]相关合同信息");
        }else{
            resp.put("issuccess", "Y");
            resp.put("msg", "存在["+vbillcode+"]相关合同信息");
        }
    }

    /**
     * 从request中获取接口数据
     * @param request 接口请求
     * */
    private String readRequest(HttpServletRequest request) throws Exception {
        InputStreamReader insr = new InputStreamReader(request.getInputStream(), "utf-8");
        StringBuffer result = new StringBuffer();
        int respInt = insr.read();
        while (respInt != -1) {
            result.append((char) respInt);
            respInt = insr.read();
        }
        if (result.length() < 1) {
            throw new BusinessException("未获取到请求体信息，请检查！");
        }
        return result.toString();
    }

    /**
     * 登录nc系统
     */
    private void loginNcSystem() {
        NCLocator.getInstance().lookup(ISecurityTokenCallback.class)
                .token("NCSystem".getBytes(), "pfxx".getBytes());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doAction(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doAction(req, resp);
    }
}
